﻿using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
using System.Linq;
using System.Xml;
using Microsoft.Data.ConnectionUI;

namespace AdHocReports.Setup
{
    [RunInstaller(true)]
    public partial class AdHocReportsInstaller : Installer
    {
        string targetdir = string.Empty;

        public AdHocReportsInstaller()
        {
            InitializeComponent();
        }

        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            targetdir = (from string dir in this.Context.Parameters.Keys
                                where dir == "targetdir"
                                select this.Context.Parameters[dir]).First();

            if (!targetdir.EndsWith("\\"))
            {
                targetdir += "\\";
            }

            RemoveSampleDataSource();

            Process p = Process.Start(targetdir + "\\bin\\AdHocReports.DataSourceEditor.exe", "\"" + targetdir.Substring(0, targetdir.Length - 1) + "\"");
            p.WaitForExit();

            if (p.ExitCode != 0)
            {
                throw new InstallException("Data source configuration aborted.");
            }
        }

        private void AddDataSource(OleDBConnectionProperties cp)
        {
            XmlDocument config = new XmlDocument();

            config.Load(targetdir + "web.config");

            XmlNode node = config.SelectSingleNode("configuration/connectionStrings");

            XmlElement connection = config.CreateElement("add");
            XmlAttribute name = config.CreateAttribute("name");
            XmlAttribute connectionString = config.CreateAttribute("connectionString");
            XmlAttribute providerName = config.CreateAttribute("providerName");

            name.Value = "AdHocReports.Properties.Settings.UserDataSource" + node.ChildNodes.Count.ToString();
            connectionString.Value = cp.ConnectionStringBuilder.ToString();
            providerName.Value = "System.Data.OleDb";

            connection.Attributes.Append(name);
            connection.Attributes.Append(connectionString);
            connection.Attributes.Append(providerName);

            node.AppendChild(connection);

            config.Save(targetdir + "web.config");
        }

        private void RemoveSampleDataSource()
        {
            XmlDocument config = new XmlDocument();

            config.Load(targetdir + "web.config");

            XmlNode node = config.SelectSingleNode("configuration/connectionStrings/add[@name=\"AdHocReports.Properties.Settings.DataSource1\"]");

            node.ParentNode.RemoveChild(node);

            config.Save(targetdir + "web.config");
        }
    }
}
